package tcdx.uap.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tcdx.uap.common.entity.AjaxResult;
import tcdx.uap.common.utils.Lutils;
import tcdx.uap.common.utils.MapUtils;
import tcdx.uap.mapper.FlowableMapper;
import tcdx.uap.service.BaseDBService;
import tcdx.uap.mapper.BaseDBMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/uap/cfg")
public class ConfigController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(ConfigController.class);
    private String prefix = "";


    @Autowired
    private FlowableMapper flowableMapper;

    @Autowired
    private BaseDBService db;

    @Autowired
    BaseDBMapper baseDBMapper;
    @Autowired
    private BaseDBService baseDBService;

    //    @RequiresPermissions("system:flowable:get_flow_mapper")
    @PostMapping("/mapper")
    @ResponseBody
    public AjaxResult mapper(@RequestBody Map<String, Object> map)
    {
        //从session中取当前登录人员信息
        Map userInfo = Lutils.genMap("user_name", "luyu1", "user_group", 9);
        Object resultData = null;
        if(map.get("mapper").equals("get_taskview_col_cfg"))
            resultData = flowableMapper.get_taskview_col_cfg(map);
        else if(map.get("mapper").equals("get_table_coulmn_relations"))
            resultData = flowableMapper.get_table_coulmn_relations(map);
        else if(map.get("mapper").equals("get_table_coulmn_by_relations"))
            resultData = flowableMapper.get_table_coulmn_by_relations(map);
        else if(map.get("mapper").equals("select_todo_counts"))
            resultData = flowableMapper.select_todo_counts(map);
        //找到表名
        return AjaxResult.success("success",resultData);
    }

    @PostMapping("/add_table_relation")
    @ResponseBody
    @Transactional
    public AjaxResult add_table_relation(@RequestBody Map<String, Object> map)
    {
        //从session中取当前登录人员信息
        String table_name = map.get("table_name").toString();
        String foreign_table_name = map.get("foreign_table_name").toString();
        String foreign_key = foreign_table_name+"_id";
        if(table_name.equals(foreign_table_name)){
            return AjaxResult.success("不能添加自身为外部关联表");
        }
        List l = db.selectEq("v_datatable_relations", Lutils.genMap("table_name", table_name,
                        "foreign_table_name", foreign_table_name));
        if(l.size()>0){
            return AjaxResult.success("已有关联关系请勿重复添加");
        }

        db.insertMap("v_datatable_relations", Lutils.genMap("table_name", table_name,
                "foreign_table_name", foreign_table_name,
                "foreign_key", foreign_key ) );
        //增加表结构的列
        baseDBMapper.tableAddColumn(MapUtils.G("tn", table_name,"columnName", foreign_key,"columnType", "NUMERIC(16, 0)"));
        //包括日志表
        baseDBMapper.tableAddColumn(MapUtils.G("tn", table_name+"_log","columnName", foreign_key,"columnType", "NUMERIC(16, 0)"));
        //找到表名
        return AjaxResult.success("success","");
    }

    @PostMapping("/del_table_relation")
    @ResponseBody
    @Transactional
    public AjaxResult del_table_relation(@RequestBody Map<String, Object> map)
    {
        Integer id = (Integer)map.get("id");
        List<Map> rlist = db.selectEq("v_datatable_relations", Lutils.genMap("id", id));
        String table_name = rlist.get(0).get("table_name").toString();
        String foreign_table_name = rlist.get(0).get("foreign_table_name").toString();
        String foreign_key = rlist.get(0).get("foreign_key").toString();
        db.deleteEq("v_datatable_relations", Lutils.genMap("id", id));
        baseDBMapper.tableDropColumn(MapUtils.G("tn", table_name,"columnName", foreign_key));
        baseDBMapper.tableDropColumn(MapUtils.G("tn", table_name+"_log","columnName", foreign_key));
        return AjaxResult.success("success");
    }

    @PostMapping("/get_table_cascading_cols")
    @ResponseBody
    @Transactional
    public AjaxResult get_table_cascading_cols(@RequestBody Map<String, Object> map)
    {
        String main_datatable = (String)map.get("main_datatable");
        List<String>relation_ids = new ArrayList<>();
        List <Map> foreignTableList=getCascadingDatatableRelations(main_datatable,relation_ids);
        return AjaxResult.success("success", foreignTableList);
    }

    public List<Map> getCascadingDatatableRelations(String main_datatable,List<String>relation_tns) {
        if(relation_tns.contains(main_datatable))
            return null;
        List<Map> tableList = new ArrayList<>();
        List<Map> columns = baseDBService.selectEq("v_datatable_columns", Lutils.genList("id", "field", "label_title","table_id"),
                Lutils.genMap("table_id", Integer.parseInt(main_datatable.substring(11,main_datatable.length()))),
                Lutils.genMap("ord", "asc"));
        for (Map m : columns) {
            m.put("value", m.get("id"));
            m.put("label", m.get("label_title"));
            m.put("isLeaf", true);
            tableList.add(m);
            relation_tns.add(main_datatable);
        }
        List<Map> foreignTableList = baseDBService.selectSql(3, Lutils.genMap("table_name", main_datatable));
        if (foreignTableList.size() > 0) {
            for (Map m : foreignTableList) {
                String foreign_table_name = m.get("foreign_table_name").toString();
                m.put("value", 100000000 + (Integer) m.get("id"));
                m.put("label", m.get("foreign_table_display_name"));
                m.put("isLeaf", false);
                m.put("children", getCascadingDatatableRelations(foreign_table_name,relation_tns));
                tableList.add(m);
            }
        }
        return tableList;
    }

    @PostMapping("/update_taskview_cols")
    @ResponseBody
    @Transactional
    public AjaxResult update_taskview_cols(@RequestBody Map<String, Object> map)
    {
        List<Integer> table_col_ids = (List<Integer>) map.get("table_col_ids");
        table_col_ids.add(-1); //防止空数据集，影响mybatis
        Integer taskview_id = (Integer) map.get("taskview_id");
        Integer maxOrd = baseDBService.selectMaxColEq("v_taskview_columns","ord", "taskview_id", taskview_id);
        maxOrd = Lutils.nvl(maxOrd,0);
        flowableMapper.delete_taskview_col(Lutils.genMap("taskview_id", taskview_id, "table_col_ids", table_col_ids));
        flowableMapper.add_taskview_col(Lutils.genMap("taskview_id", taskview_id, "table_col_ids", table_col_ids, "maxOrd", maxOrd));
        return AjaxResult.success("success");
    }


    @PostMapping("/get_taskview_columns_config")
    @ResponseBody
    public AjaxResult get_taskview_columns_config(@RequestBody Map<String, Object> map)
    {
        Integer taskview_id = (Integer)map.get("taskview_id");
        List<Map> l =flowableMapper.get_taskview_col_cfg(Lutils.genMap("taskview_id", taskview_id));
        return AjaxResult.success("success", l);
    }
}
